﻿using System.Collections;
using FlowCanvas;
using FlowCanvas.Nodes;
using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;

namespace Yoozoo.Gameplay.Liberty.Nodes
{
    [Category("Ggame")]
    public class OpenCloseUIPanel : LatentActionNodeBase
    {

        // 重试时间
        private BBParameter<float> retryInterval = 1f;
        
        public override bool allowRoutineQueueing { get { return false; } }
        [HideInInspector]
        public FlowOutput onUIClickDelegate;
        public IEnumerator Invoke(bool isOpen,string panelName,string param1,string param2,string param3)
        {
            float timer = 0;
            BlueprintUtils.OpenCloseUI(isOpen,panelName,param1,param2,param3, OnClickUI);
            if (isOpen)
            {
                yield return new UnityEngine.WaitUntil(() =>
                {
                    bool isShowing = BlueprintUtils.UIIsShowing(panelName);
                    // 如果到达重试时间还是没有显示，再次尝试打开
                    if (!isShowing)
                    {
                        timer += Time.deltaTime;
                        if (timer > retryInterval.value)
                        {
                            timer = 0;
                            UnityEngine.Debug.LogWarning($"OpenCloseUIPanel {panelName} retry open");
                            BlueprintUtils.OpenCloseUI(isOpen,panelName,param1,param2,param3, OnClickUI);
                        }
                    }
                    return isShowing;
                });
            }
            else
            {
                yield return null;
            }
        }

        private void OnClickUI()
        {
            onUIClickDelegate?.Call(new Flow());
        }


        protected override void OnRegisterDerivedPorts(FlowNode node) {
            var p1 = node.AddValueInput<bool>(parameters[0].Name);
            var p2 = node.AddValueInput<string>(parameters[1].Name);
            var p3 = node.AddValueInput<string>(parameters[2].Name);
            var p4 = node.AddValueInput<string>(parameters[3].Name);
            var p5 = node.AddValueInput<string>(parameters[4].Name);

            onUIClickDelegate = node.AddFlowOutput("onUIClickDelegate");

            node.AddFlowInput("In", (f) =>
            {
                StopCoroutine();
                Begin(Invoke(p1.value, p2.value, p3.value, p4.value,p5.value), f);
            });
        }
    }
}
